// 商品展示功能模块
// Product display module

document.addEventListener('DOMContentLoaded', function() {
    // 获取商品数据并随机选择10个
    // Get product data and randomly select 10 items
    const allProducts = getAllProducts();
    const selectedProducts = getRandomProducts(allProducts, 10);
    
    // 渲染商品卡片
    // Render product cards
    renderProductCards(selectedProducts);
});

function getAllProducts() {
    // 合并所有类别的商品到单个数组
    // Merge products from all categories
    let allProducts = [];
    for (const category in products) {
        allProducts = allProducts.concat(products[category]);
    }
    return allProducts;
}

function getRandomProducts(productsArray, count) {
    // 使用Fisher-Yates算法洗牌数组并取前N项
    // Shuffle array using Fisher-Yates algorithm and take first N items
    const shuffled = [...productsArray];
    for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled.slice(0, count);
}

function renderProductCards(products) {
    const container = document.getElementById('product-container');
    if (!container) return;

    products.forEach(product => {
        const card = document.createElement('div');
        card.className = 'product-card';
        
        // 文字内容区域
        // Text content area
        const contentDiv = document.createElement('div');
        contentDiv.className = 'product-content';
        contentDiv.innerHTML = `
            <h3>${product.name}</h3>
            <p>价格: ¥${product.price.toFixed(2)}</p>
            <p>${product.description || '暂无描述'}</p>
        `;
        
        // 图片区域
        // Image area
        const img = document.createElement('img');
        img.className = 'product-image';
        img.src = product.imageUrl || 'https://picsum.photos/300/200?random=' + Math.random();
        img.alt = product.name;
        
        card.appendChild(contentDiv);
        card.appendChild(img);
        container.appendChild(card);
    });
}